extends NodeState

@export var igorBoss: IgorBoss

# 最后一次攻击时间
var last_attack_time: float = 0.0
# 二段攻击时间
var last_alt_attack_time: float = 0.0
# 是否进行二段攻击
var punch_alt: bool


func _on_process(_delta : float) -> void:
	process_attack()
	process_punch_coillder()


func _on_enter() -> void:
	punch_alt = false


func _on_exit() -> void:
	set_monitoring_enabled(false)


func set_monitoring_enabled(enabled: bool):
	igorBoss.damageEmitter.set_deferred("monitoring", enabled)


func process_attack():
	if punch_alt:
		process_punch_alt()
	else:
		process_punch()


func process_punch():
	# 超过了两次攻击的间隔时间才能进入攻击准备
	if Time.get_ticks_msec() - last_attack_time < igorBoss.duration_between_hits:
		transition_state(IgorBoss.STATE_IDLE)
		return

	# 打开监听，允许发生碰撞
	set_monitoring_enabled(true)
	process_animation()


func process_punch_alt():
	# 尚未达到二段攻击的时间前，先播放IDEL动画，达到后判断攻击距离决定下一步
	if Time.get_ticks_msec() - last_alt_attack_time < igorBoss.duration_alt_hit:
		igorBoss.animationPlayer.play(IgorBoss.ANIMATION_IDLE)
		return

	if not igorBoss.is_player_within_attack_range():
		transition_state(IgorBoss.STATE_IDLE)
		return

	# 打开监听，允许发生碰撞
	set_monitoring_enabled(true)
	process_animation()


func process_animation():
	if punch_alt:
		igorBoss.animationPlayer.play(IgorBoss.ANIMATION_PUNCH_ALT)
	else:
		igorBoss.animationPlayer.play(IgorBoss.ANIMATION_PUNCH)


# 记录最后一次攻击时间，重置准备攻击时间
func reset_time():
	last_attack_time = Time.get_ticks_msec()
	last_alt_attack_time = Time.get_ticks_msec()


func process_punch_coillder():
	var orientation = igorBoss.character_orientation()
	if orientation == 1:
		igorBoss.damageEmitter.scale.x = 1
	elif orientation == -1:
		igorBoss.damageEmitter.scale.x = -1



func on_punch_animation_finished():
	set_monitoring_enabled(false)
	punch_alt = true
	reset_time()
	if not igorBoss.is_player_within_attack_range():
		transition_state(IgorBoss.STATE_IDLE)



func on_punch_alt_animation_finished():
	set_monitoring_enabled(false)
	punch_alt = false
	reset_time()
	transition_state(IgorBoss.STATE_IDLE)
